/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.pig4cloud.pig.ads.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pig4cloud.pig.admin.api.entity.SysUser;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.ads.gdt.service.GdtAdvertiserService;
import com.pig4cloud.pig.api.dto.AdAdverAuthDTO;
import com.pig4cloud.pig.api.entity.AdAdverAuth;
import com.pig4cloud.pig.api.entity.Advertising;
import com.pig4cloud.pig.api.gdt.entity.GdtAdvertiser;
import com.pig4cloud.pig.ads.service.AdAdverAuthService;
import com.pig4cloud.pig.ads.service.AdUserAdverService;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.api.util.Constants;
import com.pig4cloud.pig.api.util.Page;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @ 广告账户授权
 * @author john
 *
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/auth_req")
@Api(value = "auth_req", tags = "广告账户授权模块")
public class AdvAuthController {

	private final AdvService advService;

	private final GdtAdvertiserService gdtAdvertiserService;

	private final AdUserAdverService adUserAdverService;

	private final AdAdverAuthService adAdverAuthService;

	private final RemoteUserService remoteUserService;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	/**
	 * 分页查询广告账户信息
	 * @param dto 分页对象
	 * @return 分页对象
	 */
	@PostMapping("/page")
	public R getAdverPage(@RequestBody AdAdverAuthDTO dto) {
		R<List<SysUser>> data = remoteUserService.getUserList(SecurityConstants.FROM_IN);

		if(data.getCode() == 0) {
			List<SysUser> ulist = data.getData();
			//Map<Integer, String> userMap = ulist.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getUsername));
			//Map<Integer, String> userMap = ulist.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getRealName));
			Map<Integer, String> userMap = ulist.stream().collect(HashMap::new, (m,v)->m.put(v.getUserId(), v.getUsername()), HashMap::putAll);
			//查询自身拥有的管家账户，以及该账号下的所有普通账号。普通用户不可授权申请账号为自身。管家账号可以授权管家账号名下的所有账号的申请
			List<String> ttList = advService.getAuthAdvList();
			List<String> gdtList = gdtAdvertiserService.getAuthAdvList();

			if(CollectionUtils.isEmpty(ttList) && CollectionUtils.isEmpty(gdtList)) {
				return R.ok(new Page());
			}

			ttList.addAll(gdtList);

			IPage ipage=  adAdverAuthService.page(dto.getPage(), Wrappers.<AdAdverAuth>query().lambda().in(AdAdverAuth::getAdvertiserId, ttList).eq(dto.getStatus() != null, AdAdverAuth::getStatus, dto.getStatus()).eq(dto.getAuthStatus() != null, AdAdverAuth::getAuthStatus, dto.getAuthStatus()).orderByDesc(AdAdverAuth::getCreatetime));
			if(ipage !=null && ipage.getRecords() !=null && ipage.getRecords().size() != 0) {
				List<AdAdverAuth> list = ipage.getRecords();
				list.forEach(item -> {
					String advertiserId = item.getAdvertiserId();
					item.setName(stringRedisTemplate.opsForValue().get(Constants.AD_REDIS_AD_NAME_KEY_PRIX_ + advertiserId));
					if(PlatformTypeEnum.TT.getValue().equals(item.getPlatformId())) {
						item.setAdnum(advService.list(Wrappers.<Advertising>query().lambda().eq(Advertising::getHousekeeper, advertiserId)).size());//查询头条名下账号数量
					}else if(PlatformTypeEnum.GDT.getValue().equals(item.getPlatformId())) {
						item.setAdnum(gdtAdvertiserService.list(Wrappers.<GdtAdvertiser>query().lambda().eq(GdtAdvertiser::getHousekeeper, advertiserId)).size());//查询广点通名下账号数量
					}

					item.setCreateusername(userMap.get(item.getCreateuser()));
					item.setAuthusername(userMap.get(item.getAuthuser()));
				});
			}
			return R.ok(ipage);
		}else {
			return R.ok(new Page());
		}
	}


	@SysLog("批准广告账户")
	@PostMapping("/auth")
	//@PreAuthorize("@pms.hasPermission('adver_auth_agree')")
	public R auth(@RequestBody AdAdverAuth auth) {
		Integer authStatus = auth.getAuthStatus();
		auth.setAuthtime(new Date());
		auth.setStatus(1);//0-未审核，1-已审核
		auth.setAuthuser(SecurityUtils.getUser().getId());
		//拒绝
		if(authStatus==1) {
			return R.ok(adAdverAuthService.saveOrUpdate(auth));
		}
		return adAdverAuthService.auth(auth);
	}
}
